import htmlparse from '@/common/html-parser.js'
import {
	uniUploadFile
} from '@/common/promise.js'
import {
	img_path,HTTP_REQUEST_URL
} from '@/config.js'
// 获取页面栈 delta = n-1
const getCurrenPage = (n) => {
	let pages = getCurrentPages();
	let targetPage = pages[pages.length - n];
	return targetPage
}

/*
 *  图片缩略图路径  
 * 
 * */
const smallPath=(path)=>{	
	return HTTP_REQUEST_URL+'/image/compress?from=zdy_base&path='+path+'&isgd=1&width=200';
} 

// 日期格式化 
const dateFormat = (fmt, date) => {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}

// 坐标转换 度分秒格式
const d2Dms = (data) => {
  let d = parseInt(data);
  let m = parseInt((data - d) * 60);
  let s = Math.floor(((data - d) * 60 - m) * 60 * 100) / 100;
  return d + "°" + m + "′" + s + "″";
}

// 解析html 转 数组
const htmlParse = (html) => {
	let htmlNodes = [];
	let htmlString = '';

	htmlString = html.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
		.replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
		.replace(/<p>/ig, '<p class="html_p">')
		.replace(/<br>/ig, '<p class="html_p">')
		.replace(/<div>/ig, '<div class="html_p">')
		.replace(/<img/ig, '<img class="html_img"')
		.replace(/<img/ig, '<img class="html_img"')
		// .replace(/src=/ig, 'src="http://www.honghuoyi.com"')
		
	// .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
	// .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
	// .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
	// .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
	// .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1 class="html_img"')

	htmlNodes = htmlparse(htmlString);
	return htmlNodes;
}

/*  
 * 参数复杂路由跳转传入（object）
 * opentype:'navigate',   跳转方式 跟opentype
 * backOpenType:'navigate', 回跳方式
 * url:'/pages/member/group/group',     // 目标url
 * backurl:'',       返回路由
 * params:{type:'select',memberid:this.member.select},  	  // 目标url参数 * 
 * backparams:{type:'select',memberid:[]},   返回路由参数
 *   
 *  /pages/login/login?id=1&type=add&backurl=%%%%%%%%%%%%5
 */
const router = (data) => {
	let targetUrl = '',
		url = '',
		urlQuery = '',
		params = '',
		backUrl = '',
		backUrlParams = '',
		urlParams = '', // eg 'pages/login/login?type=a' 
		backOpenType = '';

	// 处理目标url
	// 1 判断是否带url参数
	if (data.url.indexOf('?') != -1) {
		data.url = data.url.split('?');
		url = data.url[0];
		urlQuery = data.url[1];
		params = urlQuery;
	} else {
		url = data.url;
	}

	// 处理参数
	if (data.params) {
		for (let i in data.params) {
			if (typeof(data.params[i]) == 'object') { // 处理参数值为对象时转码
				data.params[i] = objectToEncode(data.params[i])
			}
		}
		if (urlQuery) {
			params = urlQuery + '&' + jsonToQuery(data.params);
		} else {
			params = jsonToQuery(data.params);
		}
	}

	if (data.backurl) {
		if (data.backOpenType) {
			backOpenType = "&backOpenType=" + data.backOpenType;
		}
		// 回传参数
		//1 判断url是否带参数   /pages/login/login?a=1&b=2
		if (data.backurl.indexOf('?') != -1) {
			data.backurl = data.backurl.split('?')
			backUrl = data.backurl[0];
			urlParams = data.backurl[1];
			backUrlParams = urlParams;
		} else {
			backUrl = data.backurl;
		}

		if (params) {
			backUrl = "&backurl=" + backUrl;
		} else {
			backUrl = "?backurl=" + backUrl;
		}

		if (data.backparams) {
			if (backUrlParams) {
				backUrlParams = backUrlParams + '&' + jsonToQuery(data.backparams)
			} else {
				backUrlParams = jsonToQuery(data.backparams)
			}
		}
		if (backUrlParams) {
			backUrlParams = "&backparams=" + objectToEncode(backUrlParams)
		}
	}

	targetUrl = url + '?' + params + backUrl + backUrlParams + backOpenType;
	switch (data.opentype) {
		case 'navigate':
			uni.navigateTo({
				url: targetUrl,
			});
			break;
		case 'redirect':
			uni.redirectTo({
				url: targetUrl,
			});
			break;
		case 'switchTab':
			uni.redirectTo({
				url: targetUrl,
			});
			break;
		case 'reLaunch':
			uni.reLaunch({
				url: targetUrl,
			});
			break;
	}
}



/*
 * 字符串转码
 * "xxxxx"=>%7B%22id%22%3A1%7D
 * */
const queryToEncode = (data) => {
	let enCode = encodeURIComponent(data);
	return enCode
}

/*
 * 字符串解码
 * %7B%22id%22%3A1%7D=>"xxxxx"
 * */
const encodeToString = (data) => {
	let str = decodeURIComponent(data);
	return str
}

/*
 * 	url参数转对象  
 * 	eg: type=2&ca_id=1  => {type:2,ca_id:1}
 * 		[type=2,ca_id=1] => [[type,2],[ca_id,1]] =>	{type:2,ca_id:1}
 * */
const queryToJSON = (str) => {
	let query = [],
		data = {};
	let query_arr = str.split('&');
	query_arr.forEach(item => {
		let query_item = item.split('=');
		query.push(query_item)
	})
	query.forEach(item => {
		data[item[0]] = item[1]
	})
	return data
}

/*
 * json转化成url参数
 *  eg:{a:1,b:2} =  a=1&b=2
 * 
 * ***/
const jsonToQuery = (data) => {
	let jsonStr = JSON.stringify(data);
	let query = '';
	let reg1 = /[{}"]/ig; // 去掉{}"
	let reg2 = /[:]/ig; // 匹配全部:
	let reg3 = /[,]/ig; // 匹配全部,
	query = jsonStr.replace(reg1, "") // 去掉{}"
		.replace(reg2, "=") // =替换:
		.replace(reg3, "&"); // &替换,          
	return query;
}


// 检查手机号 
const checkPhone = (data) => {
	let phoneReg = /^1[2|3|4|5|6|7|8|9][0-9]{9}$/;
	if (!phoneReg.test(data)) {
		return false
	} else { 
		return true
	}
}

// 检测身份证号等
const checkIdCard = (data) => {
	let cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	if (!cardReg.test(data)) { 
		return false
	} else { 
		return true
	}
}

// 替换字符串指定位置* （手机号/身份证号）
const replaceStr = (str, index, changeStr) => {
	return str.substr(0, index) + changeStr + str.substr(index + changeStr.length);
}

/**
 * 字符串脱敏加*  替换字符串指定位置* （手机号/身份证号）
 * str 原字符串
 * index 开始索引位
 * n 替换长度   123456 879
 */ 
const replaceStrByNum = (str, index, n) => {
	var replace_str=""; 
	for(var i=0;i<4;i++){
		replace_str+='*';
	}
	return str.substr(0, index) + '****' + str.substr(index + n);
}

 

// 阻止按钮快速点击事件
const stop = function stopClickEvent(fn) {
	let that = this;
	if (that.isStop) {
		that.isStop = false;
		fn();
	} else { 
	}
}

/*
 *  
 * count:最多上传图片数量，最多9张
 * len:已上传数量
 * success:成功回调
 * 
 * */
const uploadImage = (data) => {
	let _this = this;
	let imgUrl = [],
		uploadNum = data.length,
		count = 9,
		callback = data.success,
		sourceType=[];

	if (data.maxSize && data.maxSize <= 9) {
		count = data.maxSize;
	}
	if(data.sourceType){
		sourceType=data.sourceType;
	}else{
		sourceType=['album', 'camera'];
	}

	count = count - uploadNum; // 计算剩余可上传数量

	uni.chooseImage({
		count: count, //默认9
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: sourceType, //从相册选择
		success: function(res) {
			return callback(res)
		}
	})
}


/*
 *  预览图片
 *  data.data  预览图片 数组
 *  data.index 第几张开始预览
 * */
const previewImage = (data) => { 
	let img = data.data,
		index = data.index;
	uni.previewImage({
		current: index,
		urls: img,
		loop: true,
		indicator: "number"
	})
}

/*
 *  上传文件到服务器 
 *  data.url 服务器接口
 *  data.filePath 图片本地临时地址
 *  data.name 目录名称
 *  data.formData 其他参数
 * 
 * */
const uploadToServe = (data) => { 
	let callback = data.success;
	return new Promise((resolve, reject) => {
		uniUploadFile({
			url: data.url,
			filePath: data.filePath,
			name: data.name,
			formData: data.formData, 
		}).then((up_res) => { 
			if(up_res.statusCode==200){
				let up_res_data = decodeURIComponent(up_res.data);
				up_res_data = up_res_data.replace(/[\\]/g, '');
				up_res_data = JSON.parse(up_res_data);
				
				resolve(up_res_data)
			}
		}).catch((err) => {
			reject(err)
		})
	})
}

/*
 *  导出表格数据  
 * 
 * */
const doExport = (data) => {
	let url = reqUrl[param.pagename];
	url = goto.setParam(url, param);
	exportpcdata(url, param.pname);
} 


/*
 *  导出表格数据  
 *  url 处理地址
 *  pname 导出文件名
 * 
 * */
const exportData = (url, pname) => { 
	var fs = uni.getFileSystemManager();
	
	// var rootdir = wx.env.USER_DATA_PATH + '/doc/';
	// fs.mkdir({
	// 	dirPath: rootdir,
	// 	recursive: true
	// });
	// fs.readdir({
	// 	dirPath: rootdir,
	// 	success(res) {
	// 		let files = res.files;
	// 		for (let i in files) {
	// 			fs.unlink({
	// 				filePath: rootdir + files[i]
	// 			});
	// 		}
	// 	}
	// });
	// setTimeout(function() {
	// 	const savePath = rootdir + pname + '.xlsx';
	// 	wx.downloadFile({
	// 		url: url,
	// 		header: {
	// 			"Content-Type": "application/json",
	// 			'Cookie': wx.getStorageSync('cookieKey')
	// 		},
	// 		filePath: savePath,
	// 		success: function(res) {
	// 			wx.openDocument({
	// 				filePath: savePath,
	// 				showMenu: true,
	// 				fileType: 'xlsx',
	// 				fail(e) {
	// 					wx.showToast({
	// 						title: 'error',
	// 						image: '/img/notis.png'
	// 					})
	// 				}
	// 			})
	// 		},
	// 		complete() {
	// 			wx.hideLoading();
	// 		}
	// 	})
	// }, 300);
}


/*
 *  生成随机数  
 *  n 随机数长度
 * 
 * */
const randomString = (n) =>{    
    var len = n || 32;
    var str = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; 
    var str_len = str.length;
    var result = "";
    for (var i = 0; i < len; i++){
		result += str.charAt(Math.floor(Math.random() * str_len));
	}  
    return result
}

const showPopup = (t, n) => { 
	if (t == 'show') { 
		this.flag.isFullPage = true;
		this.flag[n] = true;
	} else if (t == 'hide') {
		if(n){ 
			this.flag[n] = false;
		}else{
			for (let i in this.flag) {
				this.flag[i] = false;
			}
		}					
	}
}


export {
	getCurrenPage,
	htmlParse,
	router,
	checkPhone,
	stop,
	checkIdCard,
	queryToEncode,
	queryToJSON,
	encodeToString,
	uploadImage,
	previewImage,
	jsonToQuery,
	replaceStr,
	dateFormat,
	uploadToServe,
	doExport,
	exportData,
	d2Dms,
	randomString,
	replaceStrByNum

}
